package com.nsl.my_youlai.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nsl.my_youlai.common.exception.IllegalFrontParameters;
import com.nsl.my_youlai.common.result.PageResult;
import com.nsl.my_youlai.common.result.Result;
import com.nsl.my_youlai.common.result.UploadFileResult;
import com.nsl.my_youlai.config.ProjectPathSetting;
import com.nsl.my_youlai.model.dto.DocxTemplateDownloadInfoDto;
import com.nsl.my_youlai.model.form.TemplateDocxForm;
import com.nsl.my_youlai.model.query.DocxTemplatePageQuery;
import com.nsl.my_youlai.model.vo.docx_template.*;
import com.nsl.my_youlai.mystar.*;
import com.nsl.my_youlai.mystar.enums.NslEnumBaseI;
import com.nsl.my_youlai.mystar.enums.NslEnumMime;
import com.nsl.my_youlai.mystar.enums.NslEnumTransformException;
import com.nsl.my_youlai.mystar.enums.NslEnumUploadStatus;
import com.nsl.my_youlai.service.DocxTemplateService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/docxTemplate")
@RequiredArgsConstructor
public class DocxTemplateController {

    private final ProjectPathSetting projectPathSetting;

    private final DocxTemplateService docxTemplateService;

    @GetMapping("/page")
    public PageResult<DocxTemplateVo4Page> getDocxTemplatePage(
            DocxTemplatePageQuery queryParams
    ) {

        log.info("queryParams = {}",queryParams);
        IPage<DocxTemplateVo4Page> result = docxTemplateService.getDocxTemplatePage(queryParams);
        return PageResult.success(result);
    }

    @GetMapping("/detail/{uuid}")
    public Result<DocxTemplateDetailVo> getDocxTemplateDetailById(@PathVariable String uuid){
        DocxTemplateDetailVo docxTemplateDetailVo= docxTemplateService.getDocxTemplateDetailById(uuid);
        log.info("docxTemplateDetailVo = {}",docxTemplateDetailVo);
        return Result.success(docxTemplateDetailVo);
    }



    @PostMapping("/uploadDocxExcel")
    public Result uploadDocxExcel(String docxId,MultipartFile file)  {
        log.info("file = {}",file);
        //获取原始文件名 - 1.jpg  123.0.0.jpg
        String originalFilename = file.getOriginalFilename();

        //构造唯一的文件名 (不能重复) - uuid(通用唯一识别码) de49685b-61c0-4b11-80fa-c71e95924018
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String prefixName=originalFilename.substring(0,index);
        String uploadFileUuid= NslUtilUuid.generateUuidWithOutHyphen();
        String newFileName = prefixName+"_"+ uploadFileUuid+extname;
        log.info("新的文件名: {}", newFileName);

        //将文件存储在服务器的磁盘目录中 E:\images
        File savedFile=new File(projectPathSetting.getDocxTemplateExcelInfoUploadPath()+"\\用户名\\"+newFileName);
        log.info("savedFile.getAbsolutePath() : {}", savedFile.getAbsolutePath());
        UploadFileResultOfDocxTemplateDataSourceExcel uploadFileResultOfDocxTemplateDataSourceExcel=new UploadFileResultOfDocxTemplateDataSourceExcel();
        //todo: verify excel validate
        try {
            file.transferTo(savedFile);
            uploadFileResultOfDocxTemplateDataSourceExcel.setUploadStatusEnum(NslEnumUploadStatus.SAVE_SUCCESS);
            uploadFileResultOfDocxTemplateDataSourceExcel.setFileToken(uploadFileUuid);
            uploadFileResultOfDocxTemplateDataSourceExcel.setOriginalFileName(originalFilename);
            //todo:
            uploadFileResultOfDocxTemplateDataSourceExcel.setDocxTemplateDataSourceExcelVerifyInfo(null);

        } catch (IOException e) {
            uploadFileResultOfDocxTemplateDataSourceExcel.setUploadStatusEnum(NslEnumUploadStatus.SAVE_FAIL);
            uploadFileResultOfDocxTemplateDataSourceExcel.setFileToken(null);
            uploadFileResultOfDocxTemplateDataSourceExcel.setOriginalFileName(originalFilename);
            //todo:
            uploadFileResultOfDocxTemplateDataSourceExcel.setDocxTemplateDataSourceExcelVerifyInfo(null);
            throw new RuntimeException(e);
        }finally {
            return Result.success(uploadFileResultOfDocxTemplateDataSourceExcel);
        }
    }

    /**
     * 上传信息表
     * @param docxUuid
     * @param file
     * @return
     */
    @PostMapping("/uploadDocxInfoExcel")
    public Result uploadDocxInfoExcel(String docxUuid,MultipartFile file) {
        log.info("file = {}",file);
        //获取原始文件名 - 1.jpg  123.0.0.jpg
        UploadFileResultOfDocxTemplateDataSourceExcel uploadFileResult= docxTemplateService.uploadDocxTemplateDataSourceExcel(docxUuid,file);

        if(uploadFileResult.getUploadStatusEnum()== NslEnumUploadStatus.SAVE_SUCCESS){
            return Result.success(uploadFileResult);
        }else{
            return Result.failed(uploadFileResult.getErrorMsg());
        }
    }

    /**
     * 上传模板文件：docx或者excel
     * @param file
     * @return
     */
    @PostMapping("/uploadDocxTemplate")
    public Result uploadDocxTemplate(MultipartFile file) {
        log.info("file = {}",file);
        log.info("file.getOriginalFilename() = {}",file.getOriginalFilename());

        UploadFileResultOfDocxTemplate uploadFileResultOfDocxTemplate=docxTemplateService.uploadDocxTemplate(file);

        if(uploadFileResultOfDocxTemplate.getUploadStatusEnum()== NslEnumUploadStatus.SAVE_SUCCESS){
            return Result.success(uploadFileResultOfDocxTemplate);
        }else{
            return Result.failed(uploadFileResultOfDocxTemplate.getErrorMsg());
        }
    }




    /**
     * 下载模板 docx或者excel
     * @param response
     * @param fileType  docx 或者 xlsx
     * @throws IOException
     */
    @GetMapping("/downloadTemplate/{uuid}/{fileType}")
    public void downloadDocxTemplateFile(HttpServletResponse response, @PathVariable  String uuid, @PathVariable  String fileType) throws IOException, NslEnumTransformException {
        //todo: 是否有下载权限

        if(fileType.equals(NslEnumMime.OFFICE_DOCX.getValue())|| fileType.equals(NslEnumMime.OFFICE_XLSX.getValue())){
            File templateFile= docxTemplateService.getTemplateFile(uuid,NslEnumBaseI.getEnumByValue(fileType,NslEnumMime.class)) ;

            String fileName=NslUtilFilePath.getFileName(templateFile.getAbsolutePath());
            fileName=docxTemplateService.removeUuidTag(fileName);

            NslUtilHttpServletResponse.downloadFile(response,templateFile, NslEnumBaseI.getEnumByValue(fileType, NslEnumMime.class),fileName);
        }else{
            throw new RuntimeException("前端 fileType ="+fileType+" , fileType为非法输入");
        }
    }

    @GetMapping("/downloadTempFile/{uuid}/{originalFileName}")
    public void downloadTempFile(HttpServletResponse response, @PathVariable  String uuid, @PathVariable  String originalFileName) throws UnsupportedEncodingException, NslEnumTransformException {
        //todo: 是否有下载权限
        if(NslUtilString.notNullAndTrimBlank(uuid) && NslUtilString.notNullAndTrimBlank(originalFileName) ){
            String suffix= NslUtilFilePath.getFileExtension(originalFileName);
            NslEnumMime fileType=NslEnumBaseI.getEnumByValue(suffix,NslEnumMime.class);
            File tempFile=docxTemplateService.getTempFile(originalFileName,uuid);
            String fileName=NslUtilFilePath.getFileName(tempFile.getAbsolutePath());
            fileName=docxTemplateService.removeUuidTag(fileName);
            NslUtilHttpServletResponse.downloadFile(response,tempFile,fileType,fileName);
        }else{
            throw new IllegalFrontParameters();
        }
    }



    /**
     * 批量生成word文档，并下载
     * @param uploadFileUuidStrings 上传excel 信息表文件的,uuid
     * @param uploadFileNameStrings 上传excel 信息表文件的 文件名
     * @param docxUuid 模板id
     * @param response
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/batchCreateDocxFiles/{docxUuid}")
    public void batchCreateDocxFiles(String uploadFileUuidStrings,String uploadFileNameStrings,@PathVariable String docxUuid,HttpServletResponse response) throws UnsupportedEncodingException {
        log.info("docxUuid = {} ",docxUuid);

        log.info("uploadFileUuidList = {}",uploadFileUuidStrings);
        log.info("uploadFileNameList = {}",uploadFileNameStrings);

        List<String> uploadFileUuidList=Arrays.asList(uploadFileUuidStrings.split(","));

        List<String> uploadFileNameList=Arrays.asList(uploadFileNameStrings.split(","));

        if(uploadFileNameList.size() == uploadFileNameList.size() && uploadFileNameList.size()>0){
            DocxTemplateDownloadInfoDto docxTemplateDownloadInfoDto=null;
            try {
                docxTemplateDownloadInfoDto=docxTemplateService.buildDownloadInfoDtoOfBatchDocx(uploadFileUuidList,uploadFileNameList,docxUuid);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("buildZipOfBatchDocx ioException");
            }


            //如果没有 文件扩展名，浏览器会根据mine自动添加后缀名
            NslUtilHttpServletResponse.downloadFile(response,docxTemplateDownloadInfoDto.getDownloadFile(),docxTemplateDownloadInfoDto.getDownloadFileMime(),docxTemplateDownloadInfoDto.getDownloadFileName());
        }
    }


    @PostMapping("/add")
    public Result<Object> addDocxTemplate(@RequestBody TemplateDocxForm templateDocxForm)  {
        NslUtilPrinter.printWithFastJsonPrettyAndNUll(templateDocxForm);
        docxTemplateService.addDocxTemplate(templateDocxForm);
        return Result.success();
    }

    @GetMapping("/templateForm/{docxUuid}")
    public Result<TemplateDocxForm> getTemplateDocxForm(@PathVariable String docxUuid){
        NslUtilPrinter.printWithFastJsonPrettyAndNUll(docxUuid);
        TemplateDocxForm templateDocxForm=docxTemplateService.getTemplateDocxForm(docxUuid);
        log.info("templateDocxForm = {}",templateDocxForm);
        return Result.success(templateDocxForm);
    }

    @GetMapping("/export")
    public void exportTemplates(DocxTemplatePageQuery queryParams ,HttpServletResponse response) throws IOException {
        List<DocxTemplateExportVo> list=docxTemplateService.listExportVo(queryParams);
        response.setContentType(NslEnumMime.OFFICE_XLS.getLabel());
        log.info("queryParams = {}",queryParams);
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("模板(全量).xlsx", "UTF-8"));
        EasyExcel.write(response.getOutputStream(), DocxTemplateExportVo.class).sheet("sheet1")
                .doWrite(list);
    }

}
